package com.bcts.rrh.drawingboard;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;
import android.util.DisplayMetrics;

import android.util.Log;
import android.view.MotionEvent;
import android.opengl.GLSurfaceView;

import com.bcts.rrh.drawingboard.shapeview.Ball;
import com.bcts.rrh.drawingboard.shapeview.Circle;
import com.bcts.rrh.drawingboard.shapeview.Cone;
import com.bcts.rrh.drawingboard.shapeview.Cube;
import com.bcts.rrh.drawingboard.shapeview.Cylinder;
import com.bcts.rrh.drawingboard.shapeview.GLLine;
import com.bcts.rrh.drawingboard.shapeview.Halfsphere;
import com.bcts.rrh.drawingboard.shapeview.Parallelogram;
import com.bcts.rrh.drawingboard.shapeview.Rectangle;
import com.bcts.rrh.drawingboard.shapeview.Shape_3d;
import com.bcts.rrh.drawingboard.shapeview.StLine;
import com.bcts.rrh.drawingboard.shapeview.Triangle;
import com.bcts.rrh.drawingboard.shapeview.ZhuiTi;
import com.bcts.rrh.drawingboard.utils.IsIntersectantUtil;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import static android.content.ContentValues.TAG;
import static com.bcts.rrh.drawingboard.Constants.*;

public class MyView extends GLSurfaceView {
    private static final int NONE = 0;// 原始
    //定义一组选择状态码,0-9系统操作，20-29:绘制2D图形，30-40：绘制3D图形
    public static final int STROKE_TYPE_ERASER = 1;//橡皮檫模式
    public static final int STROKE_TYPE_DRAW = 2;//画笔模式
    public static final int STROKE_TYPE_LINE = 3;//划线模式
    public static final int STROKE_TYPE_CIRCLE = 4;//画圆模式
    public static final int STROKE_TYPE_triangle = 5;//画三角形形模式
    public static final int STROKE_TYPE_RECTANGLE = 6;//画矩形模式
    public static final int STROKE_TYPE_Parallelogram = 12;//画平行四边形模式
    public static final int MOVE = 7;// 拖动
    public static final int ROTATE=8;// 旋转
    public static final int ZOOM = 9;// 放大
    public static final int FILL=10;//  填充
    public static final int ROTATE_3D=11;//3D旋转
    //3D图形状态
    public static final int Drawball=30;//画球
    public static final int Drawcube=31;//画立方体
    public static final int Drawhalfsphere=32;//画半球体
    public static final int Drawcone=33;//画圆锥
    public static final int Drawrhombohedral=34;//画四菱锥
    public static final int Drawcylinder=35;//画圆柱体
    //纹理贴图状态
    public static final int texture1=50;//纹理1号
    public static final int texture2=51;//纹理1号
    public static final int texture3=52;//纹理1号

    public static int strokeType=STROKE_TYPE_DRAW;//模式选择，橡皮檫1，画笔2，线条3，圆形4，矩形5等,初始状态是画笔状态
    int TriangleState=0;//画三角形的状态，0代表不用画，1代表画第一条边，2代表画整个三角形
    public int screenWidth, screenHeight;//屏幕的高度和宽度
    private float mX, mY;
    private float sX, sY;
    private SceneRenderer myRenderer;//场景渲染器
    private Context mContext;
    ArrayList<SketchData> sklist;//页面数据列表
    SketchData sketchData;//当前页面数据
    public DrawBgImg bg;//背景
    ArrayList<Shape_3d> alBN;//物体列表
    Shape_3d bnShape;//声明形状
    private GLLine currentLines = null;  //当前绘制的线
    private ArrayList<GLLine> linesList ; //当前绘制线的表
    private int indexpage;//表示当前第几页
    float ratio;
    int color=Constants.penColor;
    //MainActivity mainActivity=new MainActivity();

    public MyView(Context context) {
        super(context);
        //setScreenWH();
        this.mContext = context;
        sklist=new ArrayList<SketchData>();
        sketchData=new SketchData();
        sklist.add(sketchData);
        indexpage=0;//最开始初始化第0页
        myRenderer=new SceneRenderer();//创建场景渲染器
        this.setRenderer(myRenderer);//设置渲染器
        this.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
    }

    /**
     * 实现渲染器的内部类
     */
   private class SceneRenderer implements GLSurfaceView.Renderer{
        public int textureId;//声明球ID
        public int cubeId;//声明立方体ID
        public int textureZId;//晶体纹理ID
        public int bgImg1;//田字格纹理
        public int bgImg2;//英文格纹理
        public int bgImg3;//空白格纹理
        public int bgImg4;//拼音格纹理
        public int bgImg5;//横线格纹理
        public long frameCount = 0;  //共绘制了多少帧

        public SceneRenderer(){//构造器
        }

       @Override
       public void onSurfaceCreated(GL10 gl, EGLConfig config) {
           gl.glDisable(GL10.GL_DITHER);//关闭抗抖动
           gl.glEnable(GL10.GL_MULTISAMPLE);//打开抗锯齿
           gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT,GL10.GL_FASTEST);//设置模式
           gl.glClearColor(25.0f/255.0f,67.0f/255.0f,56.0f/255.0f,1.0f);//设置屏幕背景颜色

           gl.glEnable(GL10.GL_DEPTH_TEST);//启动深度检测
           gl.glDisable(GL10.GL_LIGHTING);
           //gl.glEnable(GL10.GL_LIGHTING);//允许光照
           /*initGreenLight(gl);//初始化绿色灯
           initRedLight(gl);//初始化红色灯*/

           //initMaterial(gl);//初始化材质
           //初始化纹理
           initimage(gl);
           //获取当前页面的list数据
           alBN=sklist.get(indexpage).alBN;
           linesList=sklist.get(indexpage).linesList;
           bg=sklist.get(indexpage).bg;
       }

        private void initimage(GL10 gl) {
            cubeId=initTexture(gl,R.drawable.stone1);//初始化立方体纹理ID
            textureId=initTexture(gl,R.drawable.basketball);//初始化纹理ID
            textureZId=initTexture(gl,R.drawable.stone);
            bgImg1=initTexture(gl,R.drawable.bgimg1);
            bgImg2=initTexture(gl,R.drawable.bgimg2);
            bgImg3=initTexture(gl,R.drawable.bgimg3);
            bgImg4=initTexture(gl,R.drawable.bgimg02);
            bgImg5=initTexture(gl,R.drawable.bgimg5);
        }

        @Override
       public void onSurfaceChanged(GL10 gl, int width, int height) {
            //Log.e(TAG, "onSurfaceChanged: width="+width+",height="+height );
            screenWidth=width;
            screenHeight=height;
           gl.glViewport(0,0,width,height);//设置视口大小和位置
           gl.glMatrixMode(GL10.GL_PROJECTION);//设置矩阵为投影矩阵
           gl.glLoadIdentity();//设置矩阵为单位矩阵

           ratio=(float)width/height;//比例大小
           //gl.glFrustumf(-ratio,ratio,-1,1,1,10);//设置透视投影模式
           gl.glOrthof(-ratio, ratio, -1, 1, 1, 100);//调用此方法计算产生正交投影矩阵
       }

       @Override
       public void onDrawFrame(GL10 gl) {
           //gl.glEnable(GL10.GL_CULL_FACE);//设置为打开背面剪裁
           gl.glShadeModel(GL10.GL_SMOOTH);//设置着色模型为平滑着色
//           initLight0(gl);//初始化白色灯
//           initMaterial(gl);//初始化材质为白色
//           gl.glDisable(GL10.GL_LIGHT0);	//每次绘制前，取消已开启的灯光效果
//           float[] positionParams0={0,0,0,1};//最后的1表示是定位光，此为0号灯位置参数。
//           gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, positionParams0,0); //0号灯位置

           gl.glFrontFace(GL10.GL_CCW);//设置自定义卷绕顺序：逆时针为正面
           gl.glClear(GL10.GL_COLOR_BUFFER_BIT|GL10.GL_DEPTH_BUFFER_BIT);//清除缓存u
           gl.glMatrixMode(GL10.GL_MODELVIEW);//设置当前矩阵为模式矩阵
           gl.glLoadIdentity();//设置当前矩阵为单位矩阵

           gl.glTranslatef(0,0,-2.0f);//把坐标系往z轴负方向平移2.0f个单位
           bg.drawSelf(gl);
           gl.glPushMatrix();//保护变换矩阵现场
           //将list中的所有形状遍历
           for(int i=0;i<alBN.size();i++)
           {
               gl.glPushMatrix();
               alBN.get(i).drawSelf(gl);
               gl.glPopMatrix();
           }
           gl.glPopMatrix();

           // 重置当前的模型观察矩阵
           gl.glLoadIdentity();
           //绘制线段
           drawModel(gl);


       }
        public void drawModel(GL10 gl) {
            gl.glTranslatef(0, 0, -2f); //必须有,z轴可以用于做缩放，按16比9来做，只要右下角象限
            for(int i=0;i<linesList.size();i++)
            {
                gl.glPushMatrix();
                linesList.get(i).drawSelf(gl);
                gl.glPopMatrix();
            }

            frameCount++;
        }
   }

    /*private void setScreenWH() {//获取屏幕的宽度和高度
        DisplayMetrics dm =  this.getResources().getDisplayMetrics();
        //剔除屏幕左侧工具栏,根据平板的规格修改的
        screenWidth = dm.widthPixels-195;
        screenHeight = dm.heightPixels-81;
        Log.e(TAG, "setScreenWH: screenWidth"+screenWidth+",screenHeight"+screenHeight);
//        screenWidth = dm.widthPixels;
//        screenHeight = dm.heightPixels;
    }*/
    public void setMode(int mode)//设置模式
    {
        this.strokeType=mode;
    }
    public void clearall()//清除所有形状
    {
        this.alBN.clear();
        this.linesList.clear();
        requestRender();//请求重新渲染渲染画面
    }
    public void setBgImg(String drawableId){
        //放在bg空指针
        if(bg==null){
            bg=new DrawBgImg(-1);
        }
        switch (drawableId){
            case "田字格"://田字格
                bg.setTexId(myRenderer.bgImg1);
                break;
            case "英文格"://英文格
                bg.setTexId(myRenderer.bgImg2);
                break;
            case "空白格"://空白格
                bg.setTexId(myRenderer.bgImg3);
                break;
            case "拼音格"://拼音格
                bg.setTexId(myRenderer.bgImg4);
                break;
            case "横线格"://横线格
                bg.setTexId(myRenderer.bgImg5);
                break;
            default://否则空白页
                bg.setTexId(-1);
                break;
        }
    }
    //创建新页面
    public int createpage(){
       //1。保存原来旧页面数据
        //2.创建新页面
        sketchData=new SketchData();
        sklist.add(sketchData);
        indexpage++;
        alBN=sklist.get(indexpage).alBN;
        linesList=sklist.get(indexpage).linesList;
        bg=sklist.get(indexpage).bg;
        requestRender();
       return sklist.size();
    }
    //删除当前页,返回值第一条数据代表是否成功，第2条数据当前页码数，第3条数据总页码数
    public int[] deletepage(){
       int suceess=0;//0代表没删除，1代表删除成功
       if(sklist.size()>1){
           sklist.remove(indexpage);//删除当前页
           if(indexpage>0){
               indexpage--;//不用减，因为已经删除
           }
           alBN=sklist.get(indexpage).alBN;
           linesList=sklist.get(indexpage).linesList;
           bg=sklist.get(indexpage).bg;
           requestRender();
           suceess=1;
       }
        else {//只有1页
            suceess=0;
       }

        int[] returnpage={suceess,indexpage+1,sklist.size()};
       return returnpage;
    }
    //向上翻页
    public int[] backpage(){
        int suceess=0;//0代表没删除，1代表删除成功
        if(indexpage>0){
            indexpage--;
            alBN=sklist.get(indexpage).alBN;
            linesList=sklist.get(indexpage).linesList;
            bg=sklist.get(indexpage).bg;
            requestRender();
            suceess=1;
        }
        else {//只有1页
            suceess=0;
        }
        int[] returnpage={suceess,indexpage+1,sklist.size()};
        return returnpage;
    }
    //向下翻页
    public int[] uppage(){
        int suceess=0;//0代表没删除，1代表删除成功
        if(indexpage<sklist.size()-1){
            indexpage++;
            alBN=sklist.get(indexpage).alBN;
            linesList=sklist.get(indexpage).linesList;
            bg=sklist.get(indexpage).bg;
            requestRender();
            suceess=1;
        }
        else {//只有末页
            suceess=0;
        }
        int[] returnpage={suceess,indexpage+1,sklist.size()};
        return returnpage;
    }
    int bodyFlag=-1;//表示选中物体对象
    //缩放时两手指间的距离
    float startDist=0;
    float endDist=0;
    ArrayList<Float> point=new ArrayList<Float>();
    @Override
    public boolean onTouchEvent( MotionEvent event) {
        int nCnt = event.getPointerCount();//表示手机屏幕上手指的个数
        float x = event.getX();//获取手指触碰点的X坐标
        float y = event.getY();//获取手指触碰点的Y坐标
        switch (strokeType){
            case ZOOM://放大
                switch (event.getAction()){
                    case MotionEvent.ACTION_POINTER_DOWN://第2-n个触点放下
                        float xlen=event.getX(0)-event.getX(1);
                        float ylen=event.getY(0)-event.getY(1);
                        startDist =(float) Math.sqrt((float)(xlen*xlen+ylen*ylen));
                        break;
                    case MotionEvent.ACTION_DOWN:
                        float newx=(2*x-screenWidth)*ratio/screenWidth;
                        float newy=(screenHeight-2*y)/screenHeight;
                        bodyFlag=findbodyFlag(newx,newy);
                        if (bodyFlag>=0) {
                            alBN.get(bodyFlag).setHilight(true);
                        }
                        break;
                    case MotionEvent.ACTION_MOVE://用户手指的移动
                        if(nCnt==2){//只有2个触点时才可进行缩放
                            //获取两指滑动后，两指间的距离
                            if(bodyFlag>=0){
                                if(alBN.get(bodyFlag).getHilight()==true){
                                    float xlen1=event.getX(0)-event.getX(1);
                                    float ylen1=event.getY(0)-event.getY(1);
                                    endDist =(float) Math.sqrt((float)(xlen1*xlen1+ylen1*ylen1));
                                    float scachange=endDist-startDist;
                                    alBN.get(bodyFlag).Hilight(scachange);
                                    requestRender();//请求重新渲染画面
                                    startDist=endDist;
                                }
                            }
                        }
                        break;
                }
                break;
            case MOVE://移动
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        float newx=(2*x-screenWidth)*ratio/screenWidth;
                        float newy=(screenHeight-2*y)/screenHeight;
                        if(nCnt==1){
                            bodyFlag=findbodyFlag(newx,newy);
                            if (bodyFlag>=0) {
                                alBN.get(bodyFlag).setMove(true);//设置可移动状态
                            }
                        }
                        break;
                    case MotionEvent.ACTION_MOVE://用户手指的移动
                        if(nCnt==1){
                            if(bodyFlag>=0){
                                if(alBN.get(bodyFlag).getMove()==true){
                                    float newdx=(2*x-screenWidth)*ratio/screenWidth;//3D距离
                                    float newdy=(screenHeight-2*y)/screenHeight;
                                    alBN.get(bodyFlag).Move(newdx,newdy);
                                    requestRender();//请求重新渲染渲染画面
                                }
                            }
                        }
                        break;
                }
                break;
            case ROTATE://旋转
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        float newx=(2*x-screenWidth)*ratio/screenWidth;
                        float newy=(screenHeight-2*y)/screenHeight;
                        bodyFlag=findbodyFlag(newx,newy);
                        if (bodyFlag>=0) {
                            alBN.get(bodyFlag).setRotate(true);//设置可移动状态
                        }
                        mX=x;sX=x;
                        mY=y;sY=y;
                        break;
                    case MotionEvent.ACTION_MOVE://用户手指的移动
                        float dy=y-mY;//滑动距离在y轴方向上的垂直距离
                        float dx=x-mX;//活动距离在x轴方向上的垂直距离
                        float dnewx=(2*x-screenWidth)*ratio/screenWidth;
                        float dnewy=(screenHeight-2*y)/screenHeight;
                        //if(Math.abs(y-sY)>10 || Math.abs(x-sX)>10){
                            if(bodyFlag>=0) {
                                if (alBN.get(bodyFlag).getRotate() == true) {
                                    alBN.get(bodyFlag).Rotate(dx, dy,dnewx,dnewy);
                                    requestRender();//请求重新渲染渲染画面
                                }
                            }
                        //}
                        mX=x;
                        mY=y;
                        break;
                }
                break;
            case STROKE_TYPE_ERASER://橡皮檫
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        float newx=(2*x-screenWidth)*ratio/screenWidth;
                        float newy=(screenHeight-2*y)/screenHeight;
                        bodyFlag=findbodyFlag(newx,newy);
                        int lineflag=findlineFlag(newx,newy);
                        if (bodyFlag>=0) {
                            if(lineflag>=0){
                                //比较谁在最上层
                                if(alBN.get(bodyFlag).getH()>linesList.get(lineflag).getH()){
                                    alBN.remove(bodyFlag);
                                }
                                else {
                                    linesList.remove(lineflag);
                                }
                            }
                            else {
                                alBN.remove(bodyFlag);
                            }
                        }
                        else {
                            if(lineflag>=0){
                                linesList.remove(lineflag);
                            }

                        }
                        break;
                }
                break;
            case Drawball://球
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        float newx=(2*x-screenWidth)*ratio/screenWidth;
                        float newy=(screenHeight-2*y)/screenHeight;
                        float z=this.alBN.size()-90;//按照画的顺序设置Z坐标
                        bnShape=new Ball(BALL_R,myRenderer.textureId,this.color,newx,newy,z);//创建球
                        alBN.add(bnShape);
                        Constants.Hnum++;//图层加1
                        bnShape.setH(Constants.Hnum);//设置当时的图层
                        bodyFlag=alBN.size()-1;//指定当前选中为画的那个球
                        alBN.get(bodyFlag).setMove(true);//初始状态可移动
                        break;
                    case MotionEvent.ACTION_MOVE://用户手指的移动
                        if(bodyFlag>=0){
                            if(alBN.get(bodyFlag).getMove()==true){
                                float newdx=(2*x-screenWidth)*ratio/screenWidth;//3D距离
                                float newdy=(screenHeight-2*y)/screenHeight;
                                alBN.get(bodyFlag).Move(newdx,newdy);
                                requestRender();//请求重新渲染渲染画面
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP://用户的手指离开屏幕
                        if(bodyFlag>0){
                            if(alBN.get(bodyFlag).getMove()==true){
                                alBN.get(bodyFlag).setMove(false);//设置不可移动
                            }
                        }
                        //this.strokeType=STROKE_TYPE_DRAW;
                        MainActivity.clickbtnstroke();
                        break;
                }
                break;
            case Drawcube://立方体
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        float newx=(2*x-screenWidth)*ratio/screenWidth;
                        float newy=(screenHeight-2*y)/screenHeight;
                        float z=this.alBN.size()-90;//按照画的顺序设置Z坐标
                        bnShape=new Cube(myRenderer.cubeId,this.color,1.0f,0.5f,0.5f,newx,newy,z);//创建柱体
                        alBN.add(bnShape);
                        Constants.Hnum++;//图层加1
                        bnShape.setH(Constants.Hnum);//设置当时的图层
                        bodyFlag=alBN.size()-1;//指定当前选中为画的那个球
                        alBN.get(bodyFlag).setMove(true);//初始状态可移动
                        break;
                    case MotionEvent.ACTION_MOVE://用户手指的移动
                        if(bodyFlag>=0){
                            if(alBN.get(bodyFlag).getMove()==true){
                                float newdx=(2*x-screenWidth)*ratio/screenWidth;//3D距离
                                float newdy=(screenHeight-2*y)/screenHeight;
                                alBN.get(bodyFlag).Move(newdx,newdy);
                                requestRender();//请求重新渲染渲染画面
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP://用户的手指离开屏幕
                        if(bodyFlag>0){
                            if(alBN.get(bodyFlag).getMove()==true){
                                alBN.get(bodyFlag).setMove(false);//设置不可移动
                            }
                        }
                        //this.strokeType=STROKE_TYPE_DRAW;
                        MainActivity.clickbtnstroke();
                        break;
                }
                break;
            case Drawrhombohedral://四菱锥
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        float newx=(2*x-screenWidth)*ratio/screenWidth;
                        float newy=(screenHeight-2*y)/screenHeight;
                        float z=this.alBN.size()-90;//按照画的顺序设置Z坐标
                        bnShape=new ZhuiTi(myRenderer.cubeId,this.color,ZHUITI_X,ZHUITI_Y,ZHUITI_Z,newx,newy,z);//创建晶体
                        alBN.add(bnShape);
                        Constants.Hnum++;//图层加1
                        bnShape.setH(Constants.Hnum);//设置当时的图层
                        bodyFlag=alBN.size()-1;//指定当前选中为画的那个球
                        alBN.get(bodyFlag).setMove(true);//初始状态可移动
                        break;
                    case MotionEvent.ACTION_MOVE://用户手指的移动
                        if(bodyFlag>=0){
                            if(alBN.get(bodyFlag).getMove()==true){
                                float newdx=(2*x-screenWidth)*ratio/screenWidth;//3D距离
                                float newdy=(screenHeight-2*y)/screenHeight;
                                alBN.get(bodyFlag).Move(newdx,newdy);
                                requestRender();//请求重新渲染渲染画面
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP://用户的手指离开屏幕
                        if(bodyFlag>0){
                            if(alBN.get(bodyFlag).getMove()==true){
                                alBN.get(bodyFlag).setMove(false);//设置不可移动
                            }
                        }
                        //this.strokeType=STROKE_TYPE_DRAW;
                        MainActivity.clickbtnstroke();
                        break;
                }
                break;
            case Drawhalfsphere://半球
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        float newx=(2*x-screenWidth)*ratio/screenWidth;
                        float newy=(screenHeight-2*y)/screenHeight;
                        float z=this.alBN.size()-90;//按照画的顺序设置Z坐标
                        bnShape=new Halfsphere(BALL_R,myRenderer.textureId,this.color,newx,newy,z);//创建球
                        alBN.add(bnShape);
                        Constants.Hnum++;//图层加1
                        bnShape.setH(Constants.Hnum);//设置当时的图层
                        bodyFlag=alBN.size()-1;//指定当前选中为画的那个球
                        alBN.get(bodyFlag).setMove(true);//初始状态可移动
                        break;
                    case MotionEvent.ACTION_MOVE://用户手指的移动
                        if(bodyFlag>=0){
                            if(alBN.get(bodyFlag).getMove()==true){
                                float newdx=(2*x-screenWidth)*ratio/screenWidth;//3D距离
                                float newdy=(screenHeight-2*y)/screenHeight;
                                alBN.get(bodyFlag).Move(newdx,newdy);
                                requestRender();//请求重新渲染渲染画面
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP://用户的手指离开屏幕
                        if(bodyFlag>0){
                            if(alBN.get(bodyFlag).getMove()==true){
                                alBN.get(bodyFlag).setMove(false);//设置不可移动
                            }
                        }
                        //this.strokeType=STROKE_TYPE_DRAW;
                        MainActivity.clickbtnstroke();
                        break;
                }
                break;
            case Drawcone://圆锥
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        float newx=(2*x-screenWidth)*ratio/screenWidth;
                        float newy=(screenHeight-2*y)/screenHeight;
                        float z=this.alBN.size()-90;//按照画的顺序设置Z坐标
                        bnShape=new Cone(BALL_R,1.2f,myRenderer.cubeId,this.color,newx,newy,z);//创建圆锥
                        alBN.add(bnShape);
                        Constants.Hnum++;//图层加1
                        bnShape.setH(Constants.Hnum);//设置当时的图层
                        bodyFlag=alBN.size()-1;//指定当前选中为画的那个球
                        alBN.get(bodyFlag).setMove(true);//初始状态可移动
                        break;
                    case MotionEvent.ACTION_MOVE://用户手指的移动
                        if(bodyFlag>=0){
                            if(alBN.get(bodyFlag).getMove()==true){
                                float newdx=(2*x-screenWidth)*ratio/screenWidth;//3D距离
                                float newdy=(screenHeight-2*y)/screenHeight;
                                alBN.get(bodyFlag).Move(newdx,newdy);
                                requestRender();//请求重新渲染渲染画面
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP://用户的手指离开屏幕
                        if(bodyFlag>0){
                            if(alBN.get(bodyFlag).getMove()==true){
                                alBN.get(bodyFlag).setMove(false);//设置不可移动
                            }
                        }
                        //this.strokeType=STROKE_TYPE_DRAW;
                        MainActivity.clickbtnstroke();
                        break;
                }
                break;
            case Drawcylinder://圆柱
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        float newx=(2*x-screenWidth)*ratio/screenWidth;
                        float newy=(screenHeight-2*y)/screenHeight;
                        float z=this.alBN.size()-90;//按照画的顺序设置Z坐标
                        bnShape=new Cylinder(0.8f,2f,myRenderer.cubeId,this.color,newx,newy,z);//创建球
                        alBN.add(bnShape);
                        Constants.Hnum++;//图层加1
                        bnShape.setH(Constants.Hnum);//设置当时的图层
                        bodyFlag=alBN.size()-1;//指定当前选中为画的那个球
                        alBN.get(bodyFlag).setMove(true);//初始状态可移动
                        break;
                    case MotionEvent.ACTION_MOVE://用户手指的移动
                        if(bodyFlag>=0){
                            if(alBN.get(bodyFlag).getMove()==true){
                                float newdx=(2*x-screenWidth)*ratio/screenWidth;//3D距离
                                float newdy=(screenHeight-2*y)/screenHeight;
                                alBN.get(bodyFlag).Move(newdx,newdy);
                                requestRender();//请求重新渲染渲染画面
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP://用户的手指离开屏幕
                        if(bodyFlag>0){
                            if(alBN.get(bodyFlag).getMove()==true){
                                alBN.get(bodyFlag).setMove(false);//设置不可移动
                            }
                        }
                        //this.strokeType=STROKE_TYPE_DRAW;
                        MainActivity.clickbtnstroke();
                        break;
                }
                break;
            case FILL://填充颜色
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        float newx=(2*x-screenWidth)*ratio/screenWidth;
                        float newy=(screenHeight-2*y)/screenHeight;
                        bodyFlag=findbodyFlag(newx,newy);
                        if (bodyFlag>=0) {
                            alBN.get(bodyFlag).setcolor(this.color);//设置1号纹理
                            requestRender();//请求重新渲染渲染画面
                        }
                        break;
                }
                break;
            case texture1://纹理1
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        float newx=(2*x-screenWidth)*ratio/screenWidth;
                        float newy=(screenHeight-2*y)/screenHeight;
                        bodyFlag=findbodyFlag(newx,newy);
                        if (bodyFlag>=0) {
                            alBN.get(bodyFlag).settexture(myRenderer.textureId);//设置1号纹理
                            requestRender();//请求重新渲染渲染画面
                        }
                        break;
                }
                break;
            case texture2://纹理2
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        float newx=(2*x-screenWidth)*ratio/screenWidth;
                        float newy=(screenHeight-2*y)/screenHeight;
                        bodyFlag=findbodyFlag(newx,newy);
                        if (bodyFlag>=0) {
                            alBN.get(bodyFlag).settexture(myRenderer.textureZId);//设置2号纹理
                            requestRender();//请求重新渲染渲染画面
                        }
                        break;
                }
                break;
            case texture3://纹理3
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        float newx=(2*x-screenWidth)*ratio/screenWidth;
                        float newy=(screenHeight-2*y)/screenHeight;
                        bodyFlag=findbodyFlag(newx,newy);
                        if (bodyFlag>=0) {
                            alBN.get(bodyFlag).settexture(myRenderer.cubeId);//设置3号纹理
                            requestRender();//请求重新渲染渲染画面
                        }
                        break;
                }
                break;
            case STROKE_TYPE_DRAW://写字模式
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        currentLines = new GLLine();
                        Constants.Hnum++;//图层加1
                        currentLines.setH(Constants.Hnum);//设置当时的图层
                        synchronized (linesList) {
                            linesList.add(currentLines);
                        }
                        break;
                    case MotionEvent.ACTION_MOVE:
                        Log.i("setPointer", String.format("x: %f, y: %f", x, y));
                        float realtiveX = (2*x-screenWidth)*ratio/screenWidth;
                        float realtiveY = (screenHeight-2*y)/screenHeight;
                        currentLines.drawLine(realtiveX, realtiveY,this.color);
                        break;
                    case MotionEvent.ACTION_UP:
                        break;
                }
                break;
            case STROKE_TYPE_CIRCLE://圆
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        float newx=(2*x-screenWidth)*ratio/screenWidth;
                        float newy=(screenHeight-2*y)/screenHeight;
                        //ball ball=new ball(BALL_R);
                        float z=this.alBN.size()-90;//按照画的顺序设置Z坐标
                        bnShape=new Circle(BALL_R,-1,this.color,newx,newy,z);//创建圆
                        alBN.add(bnShape);
                        Constants.Hnum++;//图层加1
                        bnShape.setH(Constants.Hnum);//设置当时的图层
                        bodyFlag=alBN.size()-1;//指定当前选中为画的那个球
                        alBN.get(bodyFlag).setMove(true);//初始状态可移动
                        break;
                    case MotionEvent.ACTION_MOVE://用户手指的移动
                        if(bodyFlag>=0){
                            if(alBN.get(bodyFlag).getMove()==true){
                                float newdx=(2*x-screenWidth)*ratio/screenWidth;//3D距离
                                float newdy=(screenHeight-2*y)/screenHeight;
                                alBN.get(bodyFlag).Move(newdx,newdy);
                                requestRender();//请求重新渲染渲染画面
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP://用户的手指离开屏幕
                        if(bodyFlag>0){
                            if(alBN.get(bodyFlag).getMove()==true){
                                alBN.get(bodyFlag).setMove(false);//设置不可移动
                            }
                        }
                        //this.strokeType=STROKE_TYPE_DRAW;
                        MainActivity.clickbtnstroke();
                        break;
                }
                break;
            case STROKE_TYPE_triangle://画三角形
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        float newx=(2*x-screenWidth)*ratio/screenWidth;
                        float newy=(screenHeight-2*y)/screenHeight;
                        float z=this.alBN.size()-90;//按照画的顺序设置Z坐标
                        bnShape=new Triangle(0,0,this.color,newx,newy,z);//创建三角形
                        alBN.add(bnShape);
                        Constants.Hnum++;//图层加1
                        bnShape.setH(Constants.Hnum);//设置当时的图层
                        bodyFlag=alBN.size()-1;//指定当前选中为画的那个球
                        break;
                    case MotionEvent.ACTION_MOVE://用户手指的移动
                        float newdx=(2*x-screenWidth)*ratio/screenWidth;
                        float newdy=(screenHeight-2*y)/screenHeight;
                        alBN.get(bodyFlag).setpoint(2,newdx,newdy);
                        requestRender();//请求重新渲染渲染画面
                        break;
                    case MotionEvent.ACTION_UP://用户的手指离开屏幕
                        if(bodyFlag>=0){
                            alBN.get(bodyFlag).meActionup();//坐标矫正
                            alBN.get(bodyFlag).setMove(false);//设置不可移动
                        }
                        //this.strokeType=STROKE_TYPE_DRAW;
                        MainActivity.clickbtnstroke();
                        break;
                }
                break;
            case STROKE_TYPE_RECTANGLE://画距形
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        float newx=(2*x-screenWidth)*ratio/screenWidth;
                        float newy=(screenHeight-2*y)/screenHeight;
                        float z=this.alBN.size()-90;//按照画的顺序设置Z坐标
                        bnShape=new Rectangle(0,0,this.color,newx,newy,z);//创建三角形
                        alBN.add(bnShape);
                        Constants.Hnum++;//图层加1
                        bnShape.setH(Constants.Hnum);//设置当时的图层
                        bodyFlag=alBN.size()-1;//指定当前选中为画的那个球
                        break;
                    case MotionEvent.ACTION_MOVE://用户手指的移动
                        float newdx=(2*x-screenWidth)*ratio/screenWidth;//3D距离
                        float newdy=(screenHeight-2*y)/screenHeight;
                        alBN.get(bodyFlag).setpoint(2,newdx,newdy);
                        requestRender();//请求重新渲染渲染画面
                        break;
                    case MotionEvent.ACTION_UP://用户的手指离开屏幕
                        if(bodyFlag>=0){
                            alBN.get(bodyFlag).meActionup();//坐标矫正
                            alBN.get(bodyFlag).setMove(false);//设置不可移动
                        }
                        //this.strokeType=STROKE_TYPE_DRAW;
                        MainActivity.clickbtnstroke();
                        break;
                }
                break;
            case STROKE_TYPE_Parallelogram://画距形
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        float newx=(2*x-screenWidth)*ratio/screenWidth;
                        float newy=(screenHeight-2*y)/screenHeight;
                        float z=this.alBN.size()-90;//按照画的顺序设置Z坐标
                        bnShape=new Parallelogram(0,0,this.color,newx,newy,z);//创建三角形
                        alBN.add(bnShape);
                        Constants.Hnum++;//图层加1
                        bnShape.setH(Constants.Hnum);//设置当时的图层
                        bodyFlag=alBN.size()-1;//指定当前选中为画的那个球
                        break;
                    case MotionEvent.ACTION_MOVE://用户手指的移动
                        float newdx=(2*x-screenWidth)*ratio/screenWidth;//3D距离
                        float newdy=(screenHeight-2*y)/screenHeight;
                        alBN.get(bodyFlag).setpoint(2,newdx,newdy);
                        requestRender();//请求重新渲染渲染画面
                        break;
                    case MotionEvent.ACTION_UP://用户的手指离开屏幕
                        if(bodyFlag>=0){
                            alBN.get(bodyFlag).meActionup();//手指离开时候执行
                            alBN.get(bodyFlag).setMove(false);//设置不可移动
                        }
                        //this.strokeType=STROKE_TYPE_DRAW;
                        MainActivity.clickbtnstroke();
                        break;
                }
                break;
            case STROKE_TYPE_LINE:
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        float newx=(2*x-screenWidth)*ratio/screenWidth;
                        float newy=(screenHeight-2*y)/screenHeight;
                        bnShape=new StLine(this.color,newx,newy,newx,newy);
                        Constants.Hnum++;//图层加1
                        bnShape.setH(Constants.Hnum);//设置当时的图层
                        alBN.add(bnShape);
                        bodyFlag=alBN.size()-1;
                        break;
                    case MotionEvent.ACTION_MOVE://用户手指的移动
                        float newdx=(2*x-screenWidth)*ratio/screenWidth;//3D距离
                        float newdy=(screenHeight-2*y)/screenHeight;
                        alBN.get(bodyFlag).setpoint(2,newdx,newdy);
                        requestRender();//请求重新渲染渲染画面
                        break;
                    case MotionEvent.ACTION_UP://用户的手指离开屏幕
                        if(bodyFlag>0){
                            if(alBN.get(bodyFlag).getMove()==true){
                                alBN.get(bodyFlag).setMove(false);//设置不可移动
                            }
                        }
                        //this.strokeType=STROKE_TYPE_DRAW;
                        break;
                }
                break;
        }
        return true;
    }

    /*
        获取选中的最上层的文字
     */
    private int findlineFlag(float newx,float newy){
        int bodyFlag = -1;//记录物体的标志位
        int Hline=0;
        for(int i=0;i<linesList.size();i++){
            int isin=linesList.get(i).ispointIn(newx,newy);
            if(isin==1) {
                if(linesList.get(i).getH()>Hline){
                    bodyFlag=i;
                    Hline=linesList.get(i).getH();
                }
            }
        }
        return bodyFlag;
    }

    private int findbodyFlag(float newx,float newy){//找到所选中的物体的方法
        ArrayList<Float> alDistance=new ArrayList<Float>();//离摄像机的距离
        alDistance.clear();//清空列表
        float bodyDistance = Float.POSITIVE_INFINITY;//记录物体距离
        int bodyFlag = -1;//记录物体的标志位

        for (int i = 0; i < alBN.size(); i++) {
            alBN.get(i).setHilight(false);
            float minMax[] = alBN.get(i).findMinMax();//获得长宽高
            float mid[] = alBN.get(i).findMid();//获取中心点位置
            float tempDistance = IsIntersectantUtil.isIntersectant
                    (
                            mid[0], mid[1], mid[2], //物体中心点位置
                            minMax[0] / 2, minMax[1] / 2, minMax[2] / 2, //长 宽 高
                            newx, newy, 2f,//A点位置
                            newx, newy, -100f//B点位置
                    );
            alDistance.add(tempDistance);
        }
        for (int i = 0; i < alDistance.size(); i++) {
            float tempA = alDistance.get(i);
            if (tempA < bodyDistance) {
                bodyDistance = tempA;//记录最小值
                bodyFlag = i;//记录最小值索引
            }
        }
        return bodyFlag;
    }




    private void initLight0(GL10 gl){
        gl.glEnable(GL10.GL_LIGHT0);//打开0号灯  ，白色
        //环境光设置
        float[] ambientParams={0.1f,0.1f,0.1f,1.0f};//光参数 RGBA
        gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_AMBIENT, ambientParams,0);
        //散射光设置
        float[] diffuseParams={0.5f,0.5f,0.5f,1.0f};//光参数 RGBA
        gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_DIFFUSE, diffuseParams,0);
        //反射光设置
        float[] specularParams={1.0f,1.0f,1.0f,1.0f};//光参数 RGBA
        gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_SPECULAR, specularParams,0);
    }

    private void initMaterial(GL10 gl){//材质为白色时什么颜色的光照在上面就将体现出什么颜色
        //环境光为白色材质
        float ambientMaterial[] = {0.4f, 0.4f, 0.4f, 1.0f};
        gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_AMBIENT, ambientMaterial,0);
        //散射光为白色材质
        float diffuseMaterial[] = {0.8f, 0.8f, 0.8f, 1.0f};
        gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_DIFFUSE, diffuseMaterial,0);
        //高光材质为白色
        float specularMaterial[] = {1.0f, 1.0f, 1.0f, 1.0f};
        gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_SPECULAR, specularMaterial,0);
        //高光反射区域,数越大高亮区域越小越暗
        float shininessMaterial[] = {1.5f};
        gl.glMaterialfv(GL10.GL_FRONT_AND_BACK, GL10.GL_SHININESS, shininessMaterial,0);

    }
    public int initTexture(GL10 gl,int drawableId)
    {
        int[] textures = new int[1];
        gl.glGenTextures(1, textures, 0);
        int currTextureId=textures[0];
        gl.glBindTexture(GL10.GL_TEXTURE_2D, currTextureId);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,GL10.GL_NEAREST);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D,GL10.GL_TEXTURE_MAG_FILTER,GL10.GL_LINEAR);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,GL10.GL_REPEAT);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,GL10.GL_REPEAT);

        InputStream is = this.getResources().openRawResource(drawableId);
        Bitmap bitmapTmp;
        try
        {
            bitmapTmp = BitmapFactory.decodeStream(is);
        }
        finally
        {
            try
            {
                is.close();
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }
        GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmapTmp, 0);
        bitmapTmp.recycle();

        return currTextureId;
    }

    public void setColor(int color){
        this.color=color;
    }
}
